package com.portal.sso.core.util;

import cn.hutool.core.util.StrUtil;
import com.portal.sso.core.config.SsoConfig;

import javax.servlet.http.HttpServletRequest;
import java.sql.Struct;
import java.util.Map;

/**
 * @program: portal-sso
 * @description: 关于header操作
 * @author: xuduo
 * @create: 2021-04-17 23:04
 * @Version: 1.0
 **/
public class RequestHeaderTools {
    /**
     * 从header中读取tgt
     * @param request
     * @return
     */
    public  static  String GetTgt(HttpServletRequest request){
        return request.getHeader(SsoConfig.SSO_HEADER_TGT);
    }

    /**
     * 给目标url地址添加参数，支持restful风格和rest风格uri
     * @param url
     * @param para
     * @param uriStyle
     * @return
     */
    public static String AddParaToUrl(String url, Map<String,String> para,String uriStyle){

        if(para==null){ return url;}
        if(StrUtil.isEmpty(uriStyle)){
            //设置默认值
            uriStyle = SsoConfig.SSO_REQUEST_URI_TYPE_REST;
        }
        if(SsoConfig.SSO_REQUEST_URI_TYPE_REST.equals(uriStyle)){
            //判断url是否带参数
            if(StrUtil.contains(url,'?')){
                for (String key:para.keySet()) {
                    url+="&"+key+"="+para.get(key);
                } ;
            }else {
                url+="?a=1";
                for (String key:para.keySet()) {
                    url+="&"+key+"="+para.get(key);
                } ;
            }
        }else if(SsoConfig.SSO_REQUEST_URI_TYPE_RESTFUL.equals(uriStyle)){
            //判断url是否带参数
                for (String key:para.keySet()) {
                    url+="/"+key+"/"+para.get(key);
                } ;
        }

        return url;
    }

    /**
     * 获取远程访问的ip
     * @param request
     * @return
     */
    public static String GetServerAndPort(HttpServletRequest request){
        return request.getRemoteAddr();
    }

    /**
     * 判断是否是https协议
     * @param request
     * @return
     */
    public static boolean CheckHttps(HttpServletRequest request){
        return request.getScheme().equals("https");
    }
}
